package com.kuaimacode.kframework.admin.services.sys;

import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SysUploadService {

    @Value("${img.upload.location.root}")
    private String fileUploadPath;

    /**
     * 上传文件通用接口
     *
     * @param request
     * @param dstFileName       html上传组件中(input中name属性)，
     * */
    public Map<String, Object> uploadFile(HttpServletRequest request, String dstFileName) {
        Map<String, Object> ret = new HashMap<String, Object>();
        //判断保存文件的路径是否存在
        File fileUploadPath = new File("E:/upload/sss");
        if (!fileUploadPath.exists()) {
            fileUploadPath.mkdir();
        }

        if (ServletFileUpload.isMultipartContent(request)) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> fileList = multipartRequest.getFiles(dstFileName);
            for (MultipartFile item : fileList) {
                String fileName = "";        //当前上传文件全名称
                String fileType = "";        //当前上传文件类型
                String saveFileName = "";    //保存到服务器目录的文件名称
                String reportAddr = "";      //保存到服务器目录的文件全路径
                try {
                    fileName = item.getOriginalFilename();
                    saveFileName = new Date().getTime() + "_" + fileName;
                    reportAddr = fileUploadPath + "/" + saveFileName;
                    reportAddr = reportAddr.replace("/", File.separator).replace("\\", File.separator);

                    File savedFile = new File(fileUploadPath, saveFileName);
                    item.transferTo(savedFile);

                    ret.put("success", true);

                } catch (Exception e) {
                    e.printStackTrace();
                    ret.put("success", false);
                    ret.put("message", e.getMessage());
                }
            }
        }
        return ret;
    }


    public static void main(String[] args){
        System.out.println(new Date().getTime());
    }

}
